<template>
  <Page class="authorize-form">
    <div class="authorize-body">
      <van-form ref="zxForm" validate-trigger="onBlur">
        <!-- 区域1 -->
        <div class="title" v-if="showFaceBtn">
          <span>基本信息</span>
        </div>
        <div v-if="showFaceBtn">
          <van-field
            v-model="form.corpName"
            label-width="140"
            readonly
            required
            name="bankName"
            label="企业名称"
            :rules="[{ required: true, message: '请选择企业基本户开户行' }]"
            input-align="right"
            placeholder="请选择"
            right-icon="arrow"
            @click="openEnterprise"
          />
          <!-- <div class="search-body" v-show="showSearch">
            <div
              v-for="(item, index) in bossList"
              :key="index"
              class="search-item"
              v-html="item.viewName"
              @click="selectOne(item)"
            ></div>
          </div> -->
          <van-field
            label-width="140"
            v-model="form.corpCredit"
            required
            disabled
            name="corpCredit"
            label="企业统一信用代码"
            placeholder="自动反显无需手填"
            input-align="right"
          />
          <van-field
            v-model="form.bankName"
            label-width="140"
            readonly
            required
            name="bankName"
            label="企业基本开户行"
            :rules="[{ required: true, message: '请选择企业基本户开户行' }]"
            input-align="right"
            placeholder="请选择"
            right-icon="arrow"
            @click="openBank1"
          />
          <van-field
            label-width="140"
            v-model="form.legalName"
            required
            disabled
            name="legalName"
            label="机构法人"
            placeholder="自动反显无需手填"
            input-align="right"
          />
          <van-field
            label-width="140"
            v-model="form.lagelPersonId"
            required
            name="lagelPersonId"
            label="法人身份证号"
            placeholder="请输入法人身份证号"
            :rules="PersonIdRules"
            input-align="right"
          />
          <!-- 区域2 -->
          <div class="title">
            <span>授权信息</span>
          </div>
          <van-field
            label-width="140"
            readonly
            required
            name="authobject"
            v-model="form.authobject"
            label="授权对象"
            :rules="[{ required: true, message: '请选择授权对象' }]"
            input-align="right"
            placeholder="请选择"
            right-icon="arrow"
            @click="openBank2"
          />
          <van-field
            readonly
            clickable
            required
            name="authdate"
            :value="form.authdate"
            input-align="right"
            label="查询期限"
            :rules="[{ required: true, message: '请选择查询期限' }]"
            placeholder="请选择"
          >
            <template #input>
              <div class="authdate_flex" slot="right-icon">
                <div class="left">
                  <van-icon name="notes-o" />
                  {{ form.startauthdate }}
                </div>
                至
                <div class="right" @click="authdateshowPicker = true">
                  <van-icon name="notes-o" />
                  {{ form.authdate }}
                </div>
              </div>
            </template>
          </van-field>
        </div>
        <!-- 人脸认证按钮 -->
        <button
          class="theme-btn"
          style="margin: 22px auto"
          @click="goFace"
          v-if="showFaceBtn"
        >
          人脸认证
        </button>
        <div class="tips">注：每次查询都需重新授权</div>
        <!-- 区域3 -->
        <div class="title" v-if="!showFaceBtn">
          <span>税务信息</span>
        </div>
        <!-- 动态表单 -->
        <div v-for="(item, index) in wfFormList" :key="index">
          <!-- input类型 -->
          <van-field
            v-if="item.type === 'input'"
            label-width="140"
            v-model="wfForm[item.id]"
            :required="item.required"
            :name="item.id"
            :label="item.label"
            :placeholder="item.placeholder"
            :rules="wfRules[item.id]"
            :disabled="item.disabled"
            @blur="handleBlur(item.id)"
            input-align="right"
          />
          <!-- dropdownSelect类型 -->
          <van-field
            v-if="item.type === 'dropdownSelect'"
            readonly
            clickable
            :name="item.id"
            :value="wfForm[item.id]"
            :label="item.label"
            required
            :rules="[{ required: true, message: '请选择' }]"
            :placeholder="item.placeholder"
            @click="openPopu(item)"
            input-align="right"
          >
          </van-field>
          <!-- smsCode类型 -->
          <van-field
            required
            :name="item.id"
            v-model="wfForm[item.id]"
            :label="item.label"
            :placeholder="item.placeholder"
            @blur="handleBlur(item.id)"
            v-if="item.type === 'smsCode'"
            :rules="[{ required: true, message: '请输入短信验证码' }]"
            label-class="sms-code"
          >
            <template #button>
              <button
                class="yzm-btn"
                type="info"
                @click="handleGetVerificationCode(item)"
                :disabled="countdown > 0"
                size="small"
              >
                {{ countdown > 0 ? `${countdown}秒后重试` : "获取验证码" }}
              </button>
            </template>
          </van-field>
        </div>
        <!-- 税务认证按钮 -->
        <button
          class="theme-btn"
          style="margin: 22px auto"
          @click="taxationCir"
          v-if="!showFaceBtn"
        >
          税务认证
        </button>
        <!-- <div class="autobook_div">
          <van-checkbox
            v-model="isreadchecked"
            disabled
            icon-size="22px"
            name="isreadchecked"
            :label-disabled="true"
            :rules="[{ required: true, message: '请先阅读授权书!' }]"
            @click="lookviewBookClick('2')"
            >我已阅读并同意</van-checkbox
          ><span class="autobook_span" @click="lookviewBookClick('2')"
            >《企业征信信息采集和查询授权书》</span
          ><span class="autobook_span" @click="lookviewBookClick('1')"
            >《企业税票数据采集授权协议书》</span
          >
        </div> -->
        <van-popup v-model="showPicker" position="bottom">
          <van-picker
            show-toolbar
            :columns="selectOptions"
            @confirm="onConfirm($event)"
            value-key="label"
            @cancel="showPicker = false"
          />
        </van-popup>
        <!-- <button
					class="theme-btn"
					style="margin: 22px auto"
					@click="nextStep"
					v-if="isLeafNode"
				>
					下一步
				</button> -->
      </van-form>
    </div>
    <!-- 搜索企业-->
    <transition name="bottomToTop05">
      <enterpriseList
        ref="bankList"
        v-if="enterpriseIshow"
        @cancel="cancelEnterpr"
        :bankList="enterpriseList"
        @clickConfirm="Confirm1Enterpr"
      ></enterpriseList>
    </transition>
    <!-- 企业基本户开户行 -->
    <transition name="bottomToTop05">
      <bankList
        ref="bankList"
        v-if="showBank1"
        @cancel="cancel1"
        :bankList="bankList1"
        @clickConfirm="clickConfirm1"
      ></bankList>
    </transition>
    <!-- 授权对象 -->
    <transition name="bottomToTop05">
      <bankList
        ref="bankList"
        v-if="showBank2"
        @cancel="cancel2"
        :bankList="bankList2"
        @clickConfirm="clickConfirm2"
      ></bankList>
    </transition>
    <!-- 日期选择 -->
    <van-popup v-model="authdateshowPicker" position="bottom">
      <van-datetime-picker
        type="date"
        title="选择年月日"
        @confirm="authdateConfirm"
        @cancel="authdateshowPicker = false"
        :min-date="minDate"
        :max-date="maxDate"
      />
    </van-popup>
    <!-- pdf -->
    <transition name="bottomToTop05">
      <view-pdf
        :pdfUrl="pdfUrl"
        :viewType="viewType"
        v-if="pdfIsShow"
        :isView="isView"
        @agreePdf="agreePdf"
      ></view-pdf>
    </transition>
    <!-- <button class="theme-btn" :class="{ disabled: canSub }" @click="submitForm">人脸认证</button> -->
    <div class="zhe-face" v-if="canLookFace">
      <van-loading size="24px" text-color="#0094ff" color="#0094ff" vertical
        >正在认证中，请稍后...</van-loading
      >
    </div>
  </Page>
</template>

<script>
import bankList from "@/components/authorize/bankList";
import enterpriseList from "@/components/authorize/enterpriseList";
import {
  getOrderedBanks,
  getCorpNames,
  faceRecognition,
  insertMes,
  getByID,
  id_number,
  companyInfoList,
  allOpenBankList,
  allOpenBankList2,
  allBankList2,
  addAuth,
} from "@/interfaces/authorize";
import { token_cydn } from "@/interfaces/cydnQt";
import viewPdf from "@/components/authorize/viewPdf.vue";
import { Dialog } from "vant";
export default {
  name: "authorize",
  components: {
    bankList,
    viewPdf,
    enterpriseList,
  },
  data() {
    return {
      enterpriseList: [],
      enterpriseIshow: false,
      // 征信form表单
      form: {
        corpName: "", // 企业名称
        corpCredit: "", // 企业统一信用代码
        legalName: "", // 机构法人
        lagelPersonId: "", // 法人身份证
        startauthdate: "", // 开始时间
        authdate: "", // 结束时间
        authobject: "", // 授权对象
        authobjectId: "", // 授权对象id
        bankName: "", // 企业基本户开户行
        bankId: "", // 企业基本户开户行id
      },
      // 微风企科技form表单
      wfFormList: [], // 动态表单
      wfForm: {
        // taxpayerId: '', // 纳税人识别号
      },
      nextWfForm: [], // 下一步的动态表单用于拼接
      wfRules: {}, // 规则
      treeId: "", // 模板id
      selectOptions: [], // 下拉内容
      applyInstr: "",
      selectBanklist2: [],
      bankList1: [],
      bankList2: [],
      showBank1: false,
      showBank2: false,
      radio: "0",
      bossList: [],
      showSearch: false,
      countdown: 0,
      countdownInterval: null,
      authdateshowPicker: false,
      minDate: "",
      maxDate: "",
      pdfIsShow: false, // 查看pdf
      isccancelpdf: false, // 是否可以关闭pdf
      isreadchecked: false, // 是否阅读了
      isLeafNode: false, // 是否展示下一步
      showFace: false, // 是否展示人脸按钮
      pdfUrl: "",
      isView: "2", // 是否阅读了，1是已阅读
      showPicker: false, // 下拉框的选择
      viewType: "",
      sqInfo: "",
      // 校验身份证号
      PersonIdRules: [
        {
          required: true,
          message: "法人身份证号不能为空",
          trigger: "onBlur",
        },
        {
          // 自定义校验规则
          validator: (value) => {
            return /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/.test(
              value
            );
          },
          message: "请输入正确格式的身份证号!",
          trigger: "onBlur",
        },
      ],
      times: "",
      canLookFace: false,
      isSuccess: "",
      showFaceBtn: false,
      userId: "",
      source: "",
    };
  },
  computed: {
    canSub() {
      return Object.values(this.form).some((val) => !val);
    },
  },
  created() {
    // 产业大脑授权判断
    // this.getByID();
    // 数据反显
    this.userId = this.getUrlParam("userId") || "";
    this.source = this.getUrlParam("source") || "";
    if (this.userId != "") {
      localStorage.setItem("spsq_userId", this.userId);
    }
    if (this.source != "") {
      localStorage.setItem("spsq_source", this.source);
    }
    this.dealData();
    this.initPage();
    // =====

    this.getIdcard();
    this.getenterpriseList();
    this.getAllOpenBankList();
  },
  watch: {
    // 'form.corpName' (newval, oldval) {

    // },
    "form.amount"(newval, oldval) {
      const test = newval ? newval.toString().replace(/^[0]+/, "") : 0;
      this.form.amount = test;
      // console.log(test)
      if (test > 100000) this.form.amount = 100000;
      if (test < 0) this.form.amount = 0;
    },
  },
  destroyed() {
    clearInterval(this.countdownInterval);
  },
  methods: {
    cancelEnterpr() {
      this.enterpriseIshow = false;
    },
    Confirm1Enterpr(item) {
      console.log(item, "是啥");
      this.form.corpName = item.bankName;
      this.form.corpCredit = item.bankId;
      this.enterpriseIshow = false;
    },
    openEnterprise() {
      this.enterpriseIshow = true;
    },
    async getAllOpenBankList() {},
    async getenterpriseList() {
      let params = {
        userId: this.userId,
        source: this.source,
      };
      console.log(params, "查询企业传值");
      const res = await companyInfoList(params);
      this.enterpriseList = res.data;

      console.log(res, "查询企业");
    },
    async getIdcard() {
      let params = {
        userId: this.userId,
        source: this.source,
      };
      console.log(params, "传的啥");
      const res = await id_number(params);
      console.log(res, "查询身份证");
      if (res.code == 200) {
        this.form.legalName = res.data.name;
        this.form.lagelPersonId = res.data.idCard;
      }
    },
    async getByID() {
      let param_token = {
        username: this.getUrlParam("phone"),
        platform: "miniApp",
      };
      const res_token = await token_cydn(param_token);
      console.log(res_token);
      if (res_token.code == 200) {
        // 更新state中的token_cydn
        this.$store.commit("user/setState", {
          attr: "token_cydn",
          data: res.token,
        });
      }
      const params = {
        id: "bcb3c3a2-9b24-4cf7-9be7-89e442f0e9b6",
      };
      const res = await getByID(params);
      console.log(res, "产业大脑税票详情");
    },
    getUrlParam(name) {
      const queryStr = String(window.location).split("?")[1] || "";
      name = encodeURIComponent(name);
      let arr = new RegExp("(^|&)" + name + "=([^&]*)(&|$)").exec(queryStr);
      if (arr) {
        return decodeURIComponent(RegExp.$2);
      } else {
        return "";
      }
    },
    dealData() {
      const code = this.getQueryStringhash("code") || "";
      const zxForm = JSON.parse(localStorage.getItem("spsqObj")) || "";
      if (code == "0" && zxForm) {
        this.showFaceBtn = false;
        // 数据反显
        this.isView = zxForm.isView;
        this.isreadchecked = this.isView == "2" ? false : true;
        delete zxForm.isView;
        this.form = { ...this.form, ...zxForm };
        // console.log(this.form, 'form');
        // 征信数据存储
        this.saveNeedForms(this.form);
        // 微风企数据初始化
        this.initWf();
      } else {
        this.showFaceBtn = true;
      }
    },

    // 保存数据
    async saveNeedForms(zxForm) {
      const params = {
        corpName: zxForm.corpName,
        corpCredit: zxForm.corpCredit,
        khh: zxForm.bankName,
        operManName: zxForm.legalName,
        cerno: zxForm.lagelPersonId,
        phone: "",
        granter: zxForm.authobject,
        startDate: zxForm.startauthdate,
        endDate: zxForm.authdate,
        // taxationMes: JSON.stringify(wfForm)
        taxAccount: "",
        taxPsw: "",
        createTime: zxForm.startauthdate,
        filePath: "",
      };
      const res = await insertMes(params);
      console.log(res, "insertMes");
    },

    openPopu(item) {
      // console.log(item, 'item');
      this.selectOptions = item.selectOptions;
      this.popuId = item.id;
      this.showPicker = true;
    },
    handleBlur(item) {
      // console.log(this.wfForm[item]);
      this.$forceUpdate();
    },
    agreePdf() {
      this.isView = "1";
      this.pdfIsShow = false;
      this.isreadchecked = true;
    },
    initPage() {
      this.form.startauthdate = this.$dayjs(new Date()).format("YYYY-MM-DD");
      this.form.authdate = this.$dayjs(new Date())
        .add(1, "year")
        .format("YYYY-MM-DD");
      this.minDate = new Date(this.$dayjs(new Date()).format("YYYY/MM/DD"));
      this.maxDate = new Date(
        this.$dayjs(new Date()).add(30, "year").format("YYYY/MM/DD")
      );
      this.getOpenBankList();
      this.getAllBankList();
    },
    wfCompany() {
      // this.getBasicInfo();
    },
    authdateConfirm(value) {
      this.form.authdate = this.$dayjs(value).format("YYYY-MM-DD");
      this.authdateshowPicker = false;
    },
    async getBossList(timer) {
      // console.log(timer, 'timer');
      // this.showSearch = true
      const params = {
        corpName: this.form.corpName,
      };
      console.log(params, "params");
      const res = await getCorpNames(params);
      console.log(res, "搜索的企业列表");
      if (this.timer === timer) {
        if (res.data.length > 0) {
          // if (res.data.length === 1) {
          //   this.form.corpName = res.data[0].corpName
          //   this.form.corpCredit = res.data[0].corpCredit
          // } else {
          res.data.forEach((ped) => {
            ped.viewName = this.deal(ped.corpName);
          });
          this.showSearch = true;
          this.bossList = res.data;
          // }
          // console.log(this.bossList, 'bossList')
        } else {
          this.showSearch = false;
        }
      }
    },
    onConfirm($event) {
      // console.log($event);

      const e = this.popuId;
      this.wfForm[e] = $event.value;
      this.showPicker = false;
    },
    async taxationCir() {
      const zxForm = JSON.parse(localStorage.getItem("spsqObj")) || "";

      console.log(this.wfForm, "params");
      console.log(this.treeId, "params2");
      console.log(zxForm, "params3");
      if (!this.hasAllPropertiesWithValues(this.wfForm)) return;
      this.canLookFace = true;
      const params2 = {
        ...this.wfForm,
        ...zxForm,
        treeId: this.treeId,
        cburl: "",
        channelCode: "51e2s",
        rpaAuthToken: this.rpaAuthToken,
      };
      params2.khh = params2.bankName;
      params2.corpCreidt = params2.corpCredit;
      params2.operManName = params2.legalName;
      params2.cerno = params2.lagelPersonId;
      params2.granterCode = params2.authobjectId;
      params2.granterName = params2.authobject;
      params2.startDate = params2.startauthdate;
      params2.endDate = params2.authdate;
      params2.taxAccount = params2.smsCode;
      params2.taxPsw = params2.password; // 税务账号密码
      params2.source = localStorage.getItem("spsq_source");
      params2.userId = localStorage.getItem("spsq_userId");
      // params2.source = "镇江市";
      // params2.userId = "c76238c8bf62415542b14b791bf654c2";
      console.log(params2, "表单提交传值");

      // ===================
      const params = {
        ...this.wfForm,
        treeId: this.treeId,
        cburl: "",
      };

      // 发票授权
      const res = await this.authorizeLogin(params);
      console.log(res, "发票授权");
      if (res.code == "200") {
        // 查询授权结果
        // this.pollApi();
        // ======
        this.canLookFace = false;
        console.log(params2, "自己传的值");
        addAuth(params2)
          .then((res) => {
            console.log(res, "自己的表单提交");
            if (res.code == "200") {
              Dialog.alert({
                title: "",
                message: "发票授权成功！",
                theme: "round-button",
                confirmButtonColor: "#008ef0",
              }).then(() => {});
            } else {
              Dialog.alert({
                title: "",
                message: res.message,
                theme: "round-button",
                confirmButtonColor: "#008ef0",
              }).then(() => {});
            }
          })
          .catch((error) => {
            Dialog.alert({
              title: "",
              message: error.message,
              theme: "round-button",
              confirmButtonColor: "#008ef0",
            }).then(() => {});
            console.log(error, "error");
          });
      } else {
        this.canLookFace = false;
        Dialog.alert({
          title: "",
          message: res.message,
          theme: "round-button",
          confirmButtonColor: "#008ef0",
        }).then(() => {});
        // this.$toast(res.message);
      }
    },
    hasAllPropertiesWithValues(obj) {
      return Object.keys(obj).findIndex((pre) => !obj[pre]) === -1
        ? true
        : false;
    },
    async getAllBankList() {
      const params = {
        area: "镇江市",
        name: "",
        type: "tax",
      };
      console.log(params, "params");
      const res = await allBankList2(params);
      console.log(res, "res222");
      res.data.forEach((element) => {
        element.bankId = element.code;
        element.bankName = element.name;
      });
      // this.bankList1 = JSON.parse(JSON.stringify(res.data));
      this.bankList2 = JSON.parse(JSON.stringify(res.data));
    },
    async getOpenBankList(name = "") {
      const params = {
        area: "镇江市",
        name: "",
      };
      console.log(params, "params");
      const res = await allOpenBankList2(params);
      console.log(res, "res111");
      res.data.forEach((element) => {
        element.bankId = element.code;
        element.bankName = element.name;
      });
      this.bankList1 = JSON.parse(JSON.stringify(res.data));
      //   this.bankList2 = JSON.parse(JSON.stringify(res.data));
    },
    async handleGetVerificationCode(item) {
      // 根据type调用不同的sdk方法
      const sendType = {
        1: "sendCaptcha",
        2: "sendAuthCaptchaCodeSm",
        3: "sendAuthCaptchaCodeFp",
        4: "sendAuthCaptchaCodeTpass",
      };
      const type = sendType[item.sendSms.type];
      console.log(item, "item");
      if (this.countdown > 0) {
        return; // 如果倒计时还在进行中，则不执行获取验证码逻辑
      }
      // 执行获取验证码逻辑，例如发送请求到后端获取验证码
      const params = {
        password: this.wfForm.password,
        username: this.wfForm.username, // 身份证号码
        messageCountDown: item.sendSms.messageCountDown,
        // employees: this.wfForm.employees,
        apiUrl: item.sendSms.apiUrl,
        buttonLabel: item.sendSms.buttonLabel,
        type: item.sendSms.type,
      };
      const res = await this.sendSms(params, type);
      console.log(res, "res");
      if (res.code == "200") {
        // 开始倒计时
        this.countdown = +item.sendSms.messageCountDown;
        const _this = this;
        this.countdownInterval = setInterval(() => {
          this.countdown--;
          if (this.countdown === 0) {
            clearInterval(_this.countdownInterval); // 倒计时结束时清除定时器
          }
        }, 1000);
      } else {
        this.$toast(res.message);
      }
    },
    // 发送短信验证
    sendSms(params, apiName) {
      console.log(params, "短信验证");
      return new Promise((resolve, reject) => {
        authSdk[apiName](params).then((res) => {
          resolve(res);
        });
      });
    },
    // 获取授权基本信息
    getBasicInfo() {
      const params = {
        taxpayerId: this.wfForm.taxpayerId,
        channelCode: "51e2s",
      };
      return new Promise((resolve, reject) => {
        authSdk.getBasicInfo(params).then((res) => {
          console.log(params, res, "获取授权基本信息");
          this.rpaAuthToken = res.data.rpaAuthToken;
          resolve(res);
        });
      });
    },
    // 省份授权模板获取
    getAuthTemplate() {
      const params = {};
      console.log(params, "省份授权模板获取");
      return new Promise((resolve, reject) => {
        authSdk.getAuthTemplate(params).then((res) => {
          resolve(res);
        });
      });
    },

    // 获取身份信息
    getAuthIdentityInfo(params) {
      console.log(params, "获取身份信息");
      params.treeId = this.treeId;
      return new Promise((resolve, reject) => {
        authSdk.getAuthIdentityInfo(params).then((res) => {
          resolve(res);
        });
      });
    },
    // 打开授权书
    lookviewBookClick(item) {
      // 如果为1代表是动态生成的授权页面
      // 如果不为1则是pdf展示
      if (item === "1") {
        this.viewType = item;
        this.pdfUrl = this.sqInfo;
        this.pdfIsShow = true;
      } else {
        this.viewType = item;
        this.pdfUrl = "/viewpdf.pdf";
        this.pdfIsShow = true;
      }
    },
    deal(val) {
      if (this.form.corpName) {
        return val.replace(
          this.form.corpName,
          "<font style='color:#fd485e;'>" + this.form.corpName + "</font>"
        );
      } else {
        return val;
      }
    },
    // 选择某个企业
    async selectOne(item) {
      this.form.corpName = item.corpName;
      this.form.corpCredit = item.corpCredit;
      // this.form.corpCredit = '321234567891011121';
      // this.form.legalName = '张聪';
      this.form.legalName = item.legalName;
      this.showSearch = false;
    },

    // 微风企
    async initWf() {
      console.log(this.form, "怎么个回事aaaa");
      // 获取微风企科技授权基本信息
      this.wfForm.taxpayerId = this.form.corpCredit;
      const res = await this.getBasicInfo();
      console.log(res, "res为什么报错");
      if (res.code === "200") {
        // 获取授权书
        this.sqInfo = res.data.taxAuthAgreement;
        const resTemplate = await this.getAuthTemplate();
        console.log(resTemplate, "resTemplate");
        // 获取动态表单value
        resTemplate.data.treeNode[0].card.keyValues
          .map((val) => val.id)
          .forEach((pre) => (this.wfForm[pre] = ""));
        console.log(this.wfForm, "wfForm");
        this.wfForm.taxpayerId = this.form.corpCredit;
        this.wfForm.companyName = this.form.corpName;
        // 模拟数据
        // this.wfForm.companyName = '江苏某某某某某有限公司';
        // this.wfForm.password = '12345678';
        // this.wfForm.username = '321234567891011121';
        // 获取规则
        this.wfRules = resTemplate.data.treeNode[0].rules;
        const ruleList = Object.values(this.wfRules);
        ruleList.forEach((pre) => {
          pre.forEach((pio) => {
            pio.trigger =
              pio.trigger === "blur"
                ? "onBlur"
                : pio.trigger === "change"
                ? "onChange"
                : pio.trigger;
          });
        });
        console.log(this.wfRules, "wfRules");
        // 取出动态表单数组
        this.wfFormList = resTemplate.data.treeNode[0].card.keyValues;
        this.wfFormList.forEach((pl) => {
          pl.required = resTemplate.data.treeNode[0].rules[pl.id][0].required;
        });
        // 模板id
        this.treeId = resTemplate.data.treeNode[0].id;
        console.log(this.treeId, "treeId");
        // 是否展示下一步
        this.isLeafNode = !resTemplate.data.treeNode[0].isLeafNode;
        this.showFace = resTemplate.data.treeNode[0].isLeafNode;
        // 下一步表单
        this.nextWfForm = this.isLeafNode
          ? resTemplate.data.treeNode[0].card.subNodes.card.keyValues
          : [];
        console.log(this.wfFormList, "wfFormList");
        // 特殊处理->身份信息固定为法定代表人
        this.wfFormList.forEach((pre) => {
          if (pre.id === "loginType") {
            pre.type = "input";
            pre.disabled = true;
            this.wfForm.loginType = "法定代表人";
          }
        });
        this.nextWfForm.forEach((pre) => {
          if (pre.id === "employees") {
            pre.type = "input";
            pre.disabled = true;
          }
        });
        console.log(this.nextWfForm, "nextWfForm");
      } else {
        this.$toast(res.message);
      }
    },

    cancel1() {
      this.showBank1 = false;
    },
    cancel2() {
      this.showBank2 = false;
    },
    clickConfirm1(item) {
      console.log(item, "itemitem");
      this.showBank1 = false;
      this.form.bankName = item.bankName;
      this.form.bankId = item.bankId;
    },
    clickConfirm2(item) {
      this.showBank2 = false;
      this.form.authobject = item.bankName;
      this.form.authobjectId = item.bankId;
    },
    nextStep() {
      if (!this.isreadchecked) {
        this.$toast("请先阅读授权书");
        return;
      }
      this.$refs.zxForm
        .validate()
        .then((result) => {
          console.log(this.form, "form");
          console.log(this.wfForm, "wfForm");
          this.nextWfStep(this.wfForm);
        })
        .catch((error) => {
          console.log(error, "error");
        });
    },
    // 微风授权登录
    authorizeLogin(params) {
      return new Promise((resolve, reject) => {
        authSdk.authorizeLogin(params).then((res) => {
          resolve(res);
        });
      });
    },
    async goFace() {
      if (!this.form.corpName || !this.form.bankName || !this.form.authobject)
        return;
      // 首先判断是否阅读
      this.zxFace();
      //   if (this.isView === "1") {
      //     this.zxFace();
      //   } else {
      //     this.$toast("请先阅读授权书");
      //   }
    },
    async pollApi() {
      this.times++;
      // 3、轮询查询授权的结果
      const resultWf = await this.getAuthrizeResult();
      console.log(resultWf, "轮询查询授权的结果");
      if (resultWf.code == "200") {
        // 授权成功
        this.canLookFace = false;
        // this.$toast("发票授权成功");
        Dialog.alert({
          title: "",
          message: "发票授权成功！",
          theme: "round-button",
          confirmButtonColor: "#008ef0",
        }).then(() => {});
        window.localStorage.removeItem("spsqObj");
      } else {
        // 再次查询
        if (this.times > 120) {
          this.canLookFace = false;
          Dialog.alert({
            title: "",
            message: "发票授权失败，请完善信息！",
            theme: "round-button",
            confirmButtonColor: "#008ef0",
          }).then(() => {});
          window.localStorage.removeItem("spsqObj");
        } else {
          const _this = this;
          setTimeout(() => {
            _this.pollApi();
          }, 1000);
        }
      }
    },
    // 获取授权结果
    getAuthrizeResult(params = {}) {
      return new Promise((resolve, reject) => {
        authSdk.getAuthrizeResult(params).then((res) => {
          resolve(res);
        });
      });
    },
    async zxFace() {
      const params = {
        name: this.form.legalName,
        idNo: this.form.lagelPersonId,
        callBackUrl:
          `https://fintech-zscqzy.szjrgzjg.com/#/invoiceAuthentication?userId=${this.userId}&source=${this.source}&code=&orderNo=&h5faceId=&newSign=`,
          // `http://192.168.1.122:8989/#/invoiceAuthentication?userId=${this.userId}&source=${this.source}&code=&orderNo=&h5faceId=&newSign=`,
      };
      const res = await faceRecognition(params);
      // const res = {
      // 	faceUrl: 'https://www.baidu.com'
      // 	// faceUrl: 'http://192.168.1.100:8989/#/attestation?code=&orderNo=&h5faceId=&newSign='
      // }
      console.log(res);
      localStorage.setItem(
        "spsqObj",
        JSON.stringify({ ...this.form, isView: this.isView })
      );
      window.location.href = res.faceUrl;
      //   if (res && res.faceUrl) {
      //     // 保存微风需要的授权参数
      //     // localStorage.setItem(
      //     // 	'wfForm',
      //     // 	JSON.stringify({
      //     // 		...this.wfForm,
      //     // 		treeId: this.treeId,
      //     // 		cburl: '',
      //     // 	})
      //     // );
      //     // 保存页面数据
      //     localStorage.setItem(
      //       "pageInfo",
      //       JSON.stringify({ ...this.form, isView: this.isView })
      //     );
      //     window.location.href = res.faceUrl;
      //   } else {
      //     this.$toast("姓名和身份证号不匹配");
      //   }
    },
    async nextWfStep(params) {
      // 获取身份信息
      const res = await this.getAuthIdentityInfo(params);
      if (res.code == "200") {
        console.log(res, "res获取身份信息");
        // 对employees下拉框进行赋值
        // const oneObj = this.nextWfForm.find((val) => val.id === 'employees');
        // oneObj.selectOptions = res.data.employees;
        // 找出法定代表人
        const oneObj = res.data.employees.find(
          (pre) => pre.value.indexOf("法定代表人") > -1
        );
        this.wfForm.employees = oneObj.value;
        this.wfFormList.push(...this.nextWfForm);
        this.isLeafNode = false;
        this.showFace = true;
        this.$forceUpdate();
      } else {
        this.$toast(res.message);
      }
    },
    // async submitForm() {
    // 	// 校验一些信息的填写格式是否真正确
    // 	// 校验手机号码
    // 	const identification = utils.regExp.get('identification');
    // 	if (!identification.test(this.form.lagelPersonId)) {
    // 		this.$toast('请先输入正确的身份证');
    // 		return;
    // 	}
    // 	if (!this.canSub) {
    // 		this.form.amount = this.form.amount + '';
    // 		const params = {
    // 			...this.form,
    // 			applyInstr: this.applyInstr,
    // 		};
    // 		console.log(params, '提交的内容');
    // 		const res = await insertFinance(params);
    // 		console.log(res, 'res');
    // 		if (res.code == 200) {
    // 			Dialog.alert({
    // 				title: '',
    // 				message: '您的需求已提交至意向银行，请继续完善问卷调查！',
    // 				theme: 'round-button',
    // 				confirmButtonColor: '#008ef0',
    // 			}).then(() => {
    // 				this.$router.push({
    // 					name: 'question',
    // 					query: {
    // 						id: res.data,
    // 					},
    // 				});
    // 			});
    // 		}
    // 	}
    // },
    openBank1() {
      this.showBank1 = true;
    },
    openBank2() {
      this.showBank2 = true;
    },
    changeSearch() {
      this.showSearch = true;
    },
    changeValue() {
      this.form.corpCredit = "";
      this.form.legalName = "";
      this.wfFormList = [];
      this.wfForm = {};
      // 代码实现
      if (this.form.corpName.length > 3) {
        this.timer = new Date().getTime();
        this.getBossList(this.timer);
      } else {
        this.showSearch = false;
      }
    },
    // 有#的情况
    getQueryStringhash(name) {
      const queryStr = String(window.location).split("?")[1] || "";
      name = encodeURIComponent(name);
      let arr = new RegExp("(^|&)" + name + "=([^&]*)(&|$)").exec(queryStr);
      if (arr) {
        return RegExp.$2;
      } else {
        return "";
      }
    },
  },
};
</script>
<style>
.van-field--error .van-field__control,
.van-field--error .van-field__control::placeholder {
  color: #c8c9cc;
}

.van-field__error-message {
  text-align: right;
}
</style>
<style lang="scss" scoped>
@import "@/assets/css/demo/index.scss";

.authorize-top {
  height: 139px;
  border: 0.5px solid transparent;
  background-image: url("https://zx-1311146360.cos.ap-shanghai.myqcloud.com/wx_h5/wx_h5_top.png");
  background-size: 100% 100%;
  background-repeat: no-repeat;

  .authorize-top-title1 {
    margin: 40px 0 0 28px;
    font-size: 21px;
    font-family: Source Han Sans SC;
    font-weight: 500;
    color: #ffffff;
  }

  .authorize-top-title2 {
    margin: 6px 0 0 28px;
    font-size: 17px;
    font-family: Source Han Sans SC;
    font-weight: 500;
    color: #ffffff;
  }
}

.authorize-form {
  position: relative;
  padding-bottom: 20px;
  height: 100%;
  overflow-y: auto;

  // border: 1px solid red;
  .title {
    width: 100%;
    height: 30px;
    background-image: url("~img/authorize/titlebg.png");
    background-size: cover;
    padding-left: 38px;
    line-height: 30px;

    span {
      font-size: 14px;
      font-weight: 550;
      color: #5094eb;
    }
  }
}

input {
  background: none;
  outline: none;
  border: none;
  text-align: right;
}

input:focus {
  border: none;
}

.bank_input {
  width: 200px;
  // border: 1px solid #e0e1e5;
  // padding: 10px 10px;
  padding-right: 8px;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: flex-end;

  .right-img {
    width: 4px;
    height: 8px;
    // border: 1px solid red;
    // position: relative;
    // bottom: -5px;
  }

  .bank_tag {
    // margin-bottom: 7px;
    // margin-right: 5px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #999999;
    // background: #f5f5f5;
    // height: 34px;
    padding: 0 5px;
    font-size: 14px;

    .bank-tag-icon {
      margin-left: 4px;
      font-size: 16px;
    }
  }
}

.selecttext {
  // width: 500rpx;
  height: 30px;
  line-height: 30px;
  text-align: right;
  color: #999999;
  font-size: 12px;
  font-family: Alibaba PuHuiTi;
  color: #999999;
}

.right-is {
  display: flex;
  justify-content: flex-end;
}

.search-body {
  position: absolute;
  top: 72px;
  right: 10px;
  width: 240px;
  max-height: 200px;
  // border: 1px solid red;
  background: #fff;
  z-index: 100;
  box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.1);
  overflow-y: auto;
  padding-bottom: 10px;

  .search-item {
    margin: 4px 0 0 8px;
    font-size: 12px;
    font-family: Alibaba PuHuiTi;
    color: #999999;
  }
}

.linkman_input {
  width: 140px;
}

.description {
  // width: 90%;
  text-align: center;

  textarea {
    width: 90%;
    padding: 4px;
    font-size: 14px;
  }
}

.authdate_flex {
  display: flex;
  font-size: 12px;

  .left {
    margin-right: 5px;
    // background-color: #f4f4f4;
    border-radius: 2px;
    padding: 0 5px;
    color: #999999;
  }

  .right {
    background-color: #f4f4f4;
    border-radius: 2px;
    padding: 0 10px;
    color: #999999;
    margin-left: 5px;
    font-size: 12px;
    box-sizing: border-box;
  }
}

.yzm-btn {
  width: 80px;
  height: 22px;
  background: #5094eb;
  border-radius: 5px;
  color: #fff;
  margin-left: 5px;
  font-size: 12px;
  // border: none;
}

// button ::after {
//   border: none;
// }
.autobook_div {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin: 0px 10px;
  font-size: 12px;

  // border: 1px solid red;
  .autobook_span {
    color: #5094eb;
    cursor: pointer;
    position: relative;
    line-height: 20px;
    // top: -2px;
  }

  /deep/.van-checkbox__label--disabled {
    color: #333;
  }

  /deep/.van-checkbox__icon--checked .van-icon {
    color: #fff;
    background-color: #1989fa;
    border-color: #1989fa;
  }
}

.zhe-face {
  position: fixed;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  z-index: 999;
  background: rgba(82, 80, 80, 0.2);
  display: flex;
  justify-content: center;
  align-items: center;
}
.tips {
  text-align: center;
  margin-top: 30px;
  font-size: 14px;
  color: rgb(252, 68, 68);
}
</style>
